package com.mcflywzx.airhockey.util;

import static android.opengl.GLES20.*;
import static android.opengl.GLUtils.texImage2D;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.*;

public class TextureHelper {
	private static final String TAG = "TextureHelper";
	
	public static int loadTexture(Context context, int resourceId, boolean isN){
		
		final int[] textureObjectIds = new int[1];
		glGenTextures(1, textureObjectIds, 0);
		if(textureObjectIds[0] == 0){
			if(Tools.CanLog){
				Log.w(TAG, "Could not generate a new OpenGL texture object.");
			}
			return 0;
		}
		//加载位图
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inScaled = false;
		final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
		
		if(bitmap == null){
			if(Tools.CanLog){
				Log.w(TAG, "Resource ID" + resourceId + "could not be decoded");
			}
			glDeleteTextures(1, textureObjectIds, 0);
			return 0;
		}
		//绑定
		glBindTexture(GL_TEXTURE_2D, textureObjectIds[0]);
		//设置默认的纹理过滤参数
		if(isN){
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		} else {
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		}
		
		//加载纹理并返回它的ID
		texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
		//回收bitmap
		bitmap.recycle();
		//生成mip贴图
		glGenerateMipmap(GL_TEXTURE_2D);
		//解除绑定
		glBindTexture(GL_TEXTURE_2D, 0);		
		
		return textureObjectIds[0];
	}
	
	public static int loadTexture(Bitmap bitmap){
		final int[] textureObjectIds = new int[1];
		glGenTextures(1, textureObjectIds, 0);
		//绑定
		glBindTexture(GL_TEXTURE_2D, textureObjectIds[0]);
		//设置默认的纹理过滤参数
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		//加载纹理并返回它的ID
		texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
		//回收bitmap
		bitmap.recycle();
		//生成mip贴图
		glGenerateMipmap(GL_TEXTURE_2D);
		//解除绑定
		glBindTexture(GL_TEXTURE_2D, 0);		
		
		return textureObjectIds[0];
	}
	
}
